package com.sddnytsh.body_buildingsystem.services

import android.content.Context
import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.*

/**
 * 健康数据管理器
 * 统一管理华为手表健康数据的获取、处理和显示
 */
class HealthDataManager(private val context: Context) {
    
    private val tag = "HealthDataManager"
    private val huaweiHealthService = HuaweiHealthService(context)
    private val permissionManager = PermissionManager(context)
    
    // 数据流
    private val _isInitialized = MutableStateFlow(false)
    val isInitialized: StateFlow<Boolean> = _isInitialized.asStateFlow()
    
    private val _isAuthorized = MutableStateFlow(false)
    val isAuthorized: StateFlow<Boolean> = _isAuthorized.asStateFlow()
    
    private val _currentHeartRate = MutableStateFlow<Int?>(null)
    val currentHeartRate: StateFlow<Int?> = _currentHeartRate.asStateFlow()
    
    private val _isDataAvailable = MutableStateFlow(false)
    val isDataAvailable: StateFlow<Boolean> = _isDataAvailable.asStateFlow()
    
    // 协程作用域
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    // 实时数据更新任务
    private var realTimeDataJob: Job? = null
    
    /**
     * 初始化健康数据管理器
     */
    suspend fun initialize(): Boolean {
        return try {
            Log.d(tag, "开始初始化健康数据管理器")
            
            // 检查权限
            if (!permissionManager.areAllPermissionsGranted()) {
                Log.w(tag, "权限未完全授予，无法初始化")
                _isInitialized.value = false
                return false
            }
            
            // 初始化华为Health Kit
            val healthKitInitialized = huaweiHealthService.initialize()
            if (!healthKitInitialized) {
                Log.e(tag, "华为Health Kit初始化失败")
                _isInitialized.value = false
                return false
            }
            
            // 检查Health Kit可用性
            val isAvailable = huaweiHealthService.isHealthKitAvailable()
            if (!isAvailable) {
                Log.w(tag, "华为Health Kit不可用")
                _isInitialized.value = false
                return false
            }
            
            _isInitialized.value = true
            Log.d(tag, "健康数据管理器初始化成功")
            true
        } catch (e: Exception) {
            Log.e(tag, "初始化失败: ${e.message}")
            _isInitialized.value = false
            false
        }
    }
    
    /**
     * 请求用户授权
     */
    suspend fun requestAuthorization(): Boolean {
        return try {
            Log.d(tag, "请求用户授权")
            val authorized = huaweiHealthService.requestAuthorization()
            _isAuthorized.value = authorized
            if (authorized) {
                Log.d(tag, "用户授权成功")
                startRealTimeDataUpdates()
            } else {
                Log.w(tag, "用户授权失败")
            }
            authorized
        } catch (e: Exception) {
            Log.e(tag, "请求授权失败: ${e.message}")
            _isAuthorized.value = false
            false
        }
    }
    
    /**
     * 开始实时数据更新
     */
    private fun startRealTimeDataUpdates() {
        realTimeDataJob?.cancel()
        realTimeDataJob = scope.launch {
            while (isActive && _isAuthorized.value) {
                try {
                    val heartRateResult = huaweiHealthService.getRealTimeHeartRate()
                    heartRateResult.fold(
                        onSuccess = { heartRate ->
                            _currentHeartRate.value = heartRate
                            _isDataAvailable.value = true
                            Log.d(tag, "获取到实时心率: $heartRate bpm")
                        },
                        onFailure = { error ->
                            Log.w(tag, "获取实时心率失败: ${error.message}")
                            _isDataAvailable.value = false
                        }
                    )
                } catch (e: Exception) {
                    Log.e(tag, "实时数据更新异常: ${e.message}")
                }
                
                // 每5秒更新一次
                delay(5000)
            }
        }
    }
    
    /**
     * 停止实时数据更新
     */
    fun stopRealTimeDataUpdates() {
        realTimeDataJob?.cancel()
        realTimeDataJob = null
        _currentHeartRate.value = null
        _isDataAvailable.value = false
    }
    
    /**
     * 获取运动期间的平均心率
     */
    suspend fun getAverageHeartRate(startTime: Long, endTime: Long): Result<Double> {
        return try {
            if (!_isInitialized.value || !_isAuthorized.value) {
                Result.failure(Exception("健康数据管理器未初始化或未授权"))
            } else {
                huaweiHealthService.getAverageHeartRate(startTime, endTime)
            }
        } catch (e: Exception) {
            Log.e(tag, "获取平均心率失败: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 获取运动期间的最大心率
     */
    suspend fun getMaxHeartRate(startTime: Long, endTime: Long): Result<Double> {
        return try {
            if (!_isInitialized.value || !_isAuthorized.value) {
                Result.failure(Exception("健康数据管理器未初始化或未授权"))
            } else {
                huaweiHealthService.getMaxHeartRate(startTime, endTime)
            }
        } catch (e: Exception) {
            Log.e(tag, "获取最大心率失败: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 获取运动期间的平均速度
     */
    suspend fun getAverageSpeed(startTime: Long, endTime: Long): Result<Double> {
        return try {
            if (!_isInitialized.value || !_isAuthorized.value) {
                Result.failure(Exception("健康数据管理器未初始化或未授权"))
            } else {
                huaweiHealthService.getSpeedData(startTime, endTime)
            }
        } catch (e: Exception) {
            Log.e(tag, "获取平均速度失败: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 获取运动期间的步数
     */
    suspend fun getStepsCount(startTime: Long, endTime: Long): Result<Int> {
        return try {
            if (!_isInitialized.value || !_isAuthorized.value) {
                Result.failure(Exception("健康数据管理器未初始化或未授权"))
            } else {
                huaweiHealthService.getStepsData(startTime, endTime)
            }
        } catch (e: Exception) {
            Log.e(tag, "获取步数失败: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 获取运动期间的距离
     */
    suspend fun getDistance(startTime: Long, endTime: Long): Result<Double> {
        return try {
            if (!_isInitialized.value || !_isAuthorized.value) {
                Result.failure(Exception("健康数据管理器未初始化或未授权"))
            } else {
                huaweiHealthService.getDistanceData(startTime, endTime)
            }
        } catch (e: Exception) {
            Log.e(tag, "获取距离失败: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 检查权限状态
     */
    fun checkPermissions(): PermissionStatus {
        val missingPermissions = permissionManager.getMissingPermissions()
        return PermissionStatus(
            allGranted = missingPermissions.isEmpty(),
            missingPermissions = missingPermissions,
            bluetoothGranted = permissionManager.isBluetoothPermissionGranted(),
            locationGranted = permissionManager.isLocationPermissionGranted(),
            bodySensorsGranted = permissionManager.isBodySensorsPermissionGranted(),
            activityRecognitionGranted = permissionManager.isActivityRecognitionPermissionGranted()
        )
    }
    
    /**
     * 获取当前状态摘要
     */
    fun getStatusSummary(): String {
        return buildString {
            appendLine("健康数据管理器状态:")
            appendLine("初始化: ${if (_isInitialized.value) "是" else "否"}")
            appendLine("已授权: ${if (_isAuthorized.value) "是" else "否"}")
            appendLine("数据可用: ${if (_isDataAvailable.value) "是" else "否"}")
            appendLine("当前心率: ${_currentHeartRate.value ?: "无数据"}")
            
            val permissionStatus = checkPermissions()
            appendLine("权限状态:")
            appendLine("  全部授予: ${if (permissionStatus.allGranted) "是" else "否"}")
            if (permissionStatus.missingPermissions.isNotEmpty()) {
                appendLine("  缺失权限: ${permissionStatus.missingPermissions.joinToString(", ")}")
            }
        }
    }
    
    /**
     * 释放资源
     */
    fun release() {
        try {
            Log.d(tag, "释放健康数据管理器资源")
            stopRealTimeDataUpdates()
            huaweiHealthService.release()
            scope.cancel()
        } catch (e: Exception) {
            Log.e(tag, "释放资源失败: ${e.message}")
        }
    }
}

/**
 * 权限状态数据类
 */
data class PermissionStatus(
    val allGranted: Boolean,
    val missingPermissions: List<String>,
    val bluetoothGranted: Boolean,
    val locationGranted: Boolean,
    val bodySensorsGranted: Boolean,
    val activityRecognitionGranted: Boolean
)
